const userMod = require('../db/userMod');
const express = require('express');
const router = express.Router();
const debug = require('debug')('a-sokio-yun:server');
const crypto = require('crypto');

// const fs = require('fs');
const { publicPath, ppxxxkkk, getServerUrl, serverPort, appName } = require('../serverOpt');

router.get('/getServerUrl', function (req, res, next) {
    res.send(getServerUrl().replace("http://", "") + ":" + serverPort);
});
router.get('/getAppName', function (req, res, next) {
    res.send(appName);
});

// 判断用户是否登录 是则跳转首页 否则跳转登录
router.get('/', function (req, res) {
    // debug("直接去首页");
    // return res.sendFile(publicPath + '/jinzhu.html');
    // res.redirect("/views/user/login.html")
    // res.redirect("/views/index备份.html")
    // res.redirect("index原版.html")
    // debug("来了主页老弟req.session", req.session);
    // debug("来了主页老弟req.headers", req.headers);
    // debug("来了主页t老弟req.query", req.query);
    if (req.session && req.session.userName) {
        res.sendFile(publicPath + '/jinzhu.html');
    } else {
        res.sendFile(publicPath + '/page/login/login.html');
    }
});

router.get('/login', function (req, res) {
    if (req.session && req.session.userName) {
        res.sendFile(publicPath + '/jinzhu.html');
    } else {
        res.sendFile(publicPath + '/page/login/login.html');
    }
});



router.post('/login', async function (req, res) {
    // debug("登录接口session", req.session);
    // debug("登录接口headers", req.headers);
    // debug("登录接口body", req.body);


    // return res.json({
    //     code: 0,
    //     msg: "登录成功"
    // })


    try {
        const { txtUserName, txtUserPwd } = req.body
        const userDoc = await userMod.findOne({ userName: txtUserName });
        if (userDoc) {
            // debug("用户信息", userDoc);
            if (userDoc.userPass.encryptedData == encryptByIv(userDoc.userPass, txtUserPwd)) {
                req.session.userName = txtUserName;
                req.session.userId = userDoc._id;
                req.session.userLevel = userDoc.userLevel;
                return res.json({
                    code: 0,
                    msg: "登录成功",
                    data: {
                        userName: txtUserName,
                        userId: userDoc._id,
                        userLevel: userDoc.userLevel,
                    }
                })
            } else {
                throw new Error("账号或密码验证失败.");
            }
        } else {
            throw new Error("账号或密码验证失败");
        }
    } catch (error) {
        debug("登录错误:", error.message);
        res.json({
            code: -1,
            msg: "登录失败:" + error.message,
            data: null,
        })
    }
});




router.post('/logout', function (req, res) {
    debug("退出登录之前req.session", req.session);
    req.session.destroy();
    debug("退出登录之后req.session", req.session);
    res.json({ code: 0, msg: "登出成功" })
});


function encryptByIv(pwdDoc, newPwdStr) {
    const iv = Buffer.from(pwdDoc.iv, 'hex');
    // console.log(iv);
    const cipher = crypto.createCipheriv('aes-256-cbc', ppxxxkkk, iv);
    let encrypted = cipher.update(newPwdStr, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
}




module.exports = router;